package com.mzxy.boxuegu.activity;

import android.content.Intent;
import android.content.SharedPreferences;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.mzxy.boxuegu.R;
import com.mzxy.boxuegu.utils.Constants;
import com.mzxy.boxuegu.utils.MD5Utils;
import com.mzxy.boxuegu.utils.SpUtils;

public class RegisterActivity extends AppCompatActivity implements View.OnClickListener{

    private EditText etUsername;
    private EditText etPwd;
    private EditText etPwdAgain;
    private Button btnRegister;

    private TextView tvMainTitle;
    private TextView tvBack;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_register);
        initView();
        initEvent();

        tvMainTitle.setText("注册");
    }

    private void initEvent() {
        btnRegister.setOnClickListener(this);
        tvBack.setOnClickListener(this);
    }

    private void initView() {
        etUsername = (EditText) findViewById(R.id.et_user_name);
        etPwd = (EditText) findViewById(R.id.et_pwd);
        etPwdAgain = (EditText) findViewById(R.id.et_pwd_again);
        btnRegister = (Button) findViewById(R.id.btn_register);
        tvMainTitle = (TextView) findViewById(R.id.tv_main_title);
        tvBack = (TextView) findViewById(R.id.tv_back);
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()){
            case R.id.btn_register:
                register();
                break;
            case R.id.tv_back:
                finish();
                break;
        }
    }

    private void register() {

        String username = etUsername.getText().toString();
        String password = etPwd.getText().toString();
        String repassword = etPwdAgain.getText().toString();

        //第一步，判断是否有输入
        if(TextUtils.isEmpty(username) || TextUtils.isEmpty(password) || TextUtils.isEmpty(repassword)){
            Toast.makeText(this,"用户名密码均不能为空",Toast.LENGTH_SHORT).show();
            return;
        }

        if(SpUtils.getPwd(this,username)!= null){
            Toast.makeText(this,"用户名"+username+"已经注册",Toast.LENGTH_SHORT).show();
            return;
        }

        //第二步，判断两个密码是否一致
        if(!password.equals(repassword)){
            Toast.makeText(this,"两次密码不一致",Toast.LENGTH_SHORT).show();
            return;
        }

        //第三步，保存用户名和密码到SharePreference
        SpUtils.saveRegisterInfo(this,username,password);
        Toast.makeText(this,"注册成功",Toast.LENGTH_SHORT).show();

        Intent data = new Intent();
        data.putExtra("username",username);
        data.putExtra("password",password);

        setResult(0x002,data);
        finish();
    }
}
